var stompClient = null;
var conTime = 0;//连接成功次数
var randomName = "user"+Math.floor(Math.random()*1000000);//随机生成用户名
var base_url_req_public_room = "/app/chatRoom" ;
var base_url_req_person_room = "/app/toUser";
var base_url_sub_public_room = '/topic/chatRoom';
var base_url_sub_person_room = '/user/topic/msg';
var courseId,url_req_public_room,url_req_person_room,url_sub_public_room,url_sub_person_room ;

function iniUrl(){
    courseId = $("#room").val();
    url_req_public_room = base_url_req_public_room+'/'+courseId;
    url_req_person_room = base_url_req_person_room+'/'+courseId;
    url_sub_public_room = base_url_sub_public_room+'.'+courseId;
    url_sub_person_room = base_url_sub_person_room+'.'+courseId;
}

function setConnected(connected) {
    conTime++ ;
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    iniUrl();
    var socket = new SockJS('../gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.heartbeat.outgoing = 10000;//心跳检测间隔毫秒
    //stompClient.heartbeat.incoming = 1;//接受服务器的回跳
    var connect_callback = function (frame) { //连接成功回调函数
        //connectCallback
        setConnected(true);
        console.log("connection successful: "+ frame);

        //订阅公共频道消息
        stompClient.subscribe(url_sub_public_room, function (greeting) {
            var parse = JSON.parse(greeting.body);
            if(parse.msgType){
                switch(parse.msgType){
                    case 'EVENT_REMOVE_MSG':removeMsg(parse.content);break;
                    default: showGreeting(parse.fromUser.realName + " - " + parse.content + (parse.toUser?parse.toUser.realName:""), parse.id);
                }
            }else{
                showGreeting(parse.fromUser.realName + " 说: " + parse.content, parse.id);
            }
        });

        // 订阅私人消息
        stompClient.subscribe(url_sub_person_room, function (greeting) {
            var parse = JSON.parse(greeting.body);
            showGreeting(parse.fromUser.realName + " 私聊说: " + parse.content, parse.id);
        });

        //发送消息，事物开启
        // var tx = stompClient.begin();
        // stompClient.send(url_req_public_room, {transaction: tx.id}, JSON.stringify({content: "加入聊天."}));
        // tx.commit();
    };
    var error_callback = function(frame){//连接失败回调函数,中途掉线也回调
        if(conTime > 0 && conTime < 100){
            console.log('聊天服务器意外断开,正在重新连接.');
            setTimeout(connect, 2000);
        }else{
            console.log('聊天服务器连接失败,请重新登录.');
        }
    };
    stompClient.connect({username: randomName}, connect_callback, error_callback);
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}
function sendMsg() {
    var url = url_req_public_room;
    var msg = {'content': $("#content").val()}
    if($("#toUser").val()!=""){
        //发送私聊
        url = url_req_person_room;
        msg.toUser = $("#toUser").val();
    }
    doSendMsg(url,msg);
}
function doSendMsg(url, object, header){
    stompClient.send(url, header?header:{}, JSON.stringify(object));
}
function showGreeting(message, id) {
    $("#greetings").append("<tr id='"+(id||Math.random())+"'><td>" + message + "</td><td><a href='javascript:btn_removeMsg(\""+id+"\")'>撤回</a></td></tr>");
}
//do撤回消息
function removeMsg(id){
    $("#"+id).remove();
}

function clean() {
    $("#greetings").html("");
}

function btn_removeMsg(id){
    var removeId = id || $("#removeMsg").val()!="";
    if(removeId) {
        var msg = {'content': removeId, "msgType": "EVENT_REMOVE_MSG"}
        doSendMsg(url_req_public_room,msg);
    }
}
function silent(){
    if($("#silent_toUser").val()!="") {
        var msg = {'toUser': $("#silent_toUser").val(), "msgType": "EVENT_USER_SILENT", "content": "禁言"}
        doSendMsg(url_req_public_room,msg);
    }
}
function unsilent(){
    if($("#silent_toUser").val()!="") {
        var msg = {'toUser': $("#silent_toUser").val(), "msgType": "EVENT_USER_UNSILENT", "content": "解禁"}
        doSendMsg(url_req_public_room,msg);
    }
}
function silentAll(){
    var msg = {"msgType": "EVENT_ALL_SILENT", "content": "全体禁言"}
    doSendMsg(url_req_public_room,msg);

}
function unsilentAll(){
    var msg = {"msgType": "EVENT_ALL_LIBERATE", "content": "全体解禁"}
    doSendMsg(url_req_public_room,msg);
}
$(function () {
    $("#name").html(randomName);
    $("form").on('submit', function (e) {e.preventDefault();});
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#clean" ).click(function() { clean(); });
    $( "#send" ).click(function() { sendMsg(); });
    $( "#send-broadcast" ).click(function() { sendMsg_broadcast(); });
    $( "#silent" ).click(silent);
    $( "#unsilent" ).click(unsilent);
    $( "#silentAll" ).click(silentAll);
    $( "#unsilentAll" ).click(unsilentAll);
    $( "#btn_removeMsg" ).click(btn_removeMsg);
});

